<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="formData.userId" placeholder="请输入用户ID" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-input v-model="formData.avatar" placeholder="请输入头像" />
      </el-form-item>
      <el-form-item label="个人简介" prop="personalProfile">
        <UploadFile v-model="formData.personalProfile" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="性别 1男 2女（字典：system_user_sex）" prop="gender">
        <el-input v-model="formData.gender" placeholder="请输入性别 1男 2女（字典：system_user_sex）" />
      </el-form-item>
      <el-form-item label="授权科目（服务一级分类ID）" prop="servicePId">
        <el-select v-model="formData.servicePId" placeholder="请选择授权科目（服务一级分类ID）">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="授权科目（服务二级分类ID）" prop="serviceId">
        <el-select v-model="formData.serviceId" placeholder="请选择授权科目（服务二级分类ID）">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="从业时间（字典：business_coach_work_time）" prop="workTime">
        <el-select v-model="formData.workTime" placeholder="请选择从业时间（字典：business_coach_work_time）">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_COACH_WORK_TIME)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态（字典：business_audit_status）" prop="auditStatus">
        <el-radio-group v-model="formData.auditStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.BUSINESS_AUDIT_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="工作状态（0休息中 1上班中）" prop="isWork">
        <el-radio-group v-model="formData.isWork">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="总评分" prop="totalScore">
        <el-input v-model="formData.totalScore" placeholder="请输入总评分" />
      </el-form-item>
      <el-form-item label="人均价格（单位分）" prop="perCapitaPrice">
        <el-input v-model="formData.perCapitaPrice" placeholder="请输入人均价格（单位分）" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { CoachApi, Coach } from '@/api/business/coach'

/** 教练信息 表单 */
defineOptions({ name: 'CoachForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  userId: undefined,
  nickname: undefined,
  avatar: undefined,
  personalProfile: undefined,
  name: undefined,
  mobile: undefined,
  gender: undefined,
  servicePId: undefined,
  serviceId: undefined,
  workTime: undefined,
  auditStatus: undefined,
  isWork: undefined,
  totalScore: undefined,
  perCapitaPrice: undefined,
})
const formRules = reactive({
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
  servicePId: [{ required: true, message: '授权科目（服务一级分类ID）不能为空', trigger: 'change' }],
  serviceId: [{ required: true, message: '授权科目（服务二级分类ID）不能为空', trigger: 'change' }],
  workTime: [{ required: true, message: '从业时间（字典：business_coach_work_time）不能为空', trigger: 'change' }],
  auditStatus: [{ required: true, message: '审核状态（字典：business_audit_status）不能为空', trigger: 'blur' }],
  isWork: [{ required: true, message: '工作状态（0休息中 1上班中）不能为空', trigger: 'blur' }],
  totalScore: [{ required: true, message: '总评分不能为空', trigger: 'blur' }],
  perCapitaPrice: [{ required: true, message: '人均价格（单位分）不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CoachApi.getCoach(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Coach
    if (formType.value === 'create') {
      await CoachApi.createCoach(data)
      message.success(t('common.createSuccess'))
    } else {
      await CoachApi.updateCoach(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    nickname: undefined,
    avatar: undefined,
    personalProfile: undefined,
    name: undefined,
    mobile: undefined,
    gender: undefined,
    servicePId: undefined,
    serviceId: undefined,
    workTime: undefined,
    auditStatus: undefined,
    isWork: undefined,
    totalScore: undefined,
    perCapitaPrice: undefined,
  }
  formRef.value?.resetFields()
}
</script>